package com.wmyg.antifake.utils;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.zip.GZIPOutputStream;

/**
 * @program: antifake
 * @description: gzip压缩工具
 * @author: wong
 * @create: 19-2-21
 */
@Slf4j
public class GZipUtils {

    public static String compress(String in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(in.getBytes(StandardCharsets.UTF_8));
        gzip.close();
//        log.info("The gziputil return data is {}", Arrays.toString(out.toByteArray()));
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(out.toByteArray());
    }

    public static String md5(String plainText) {
        //定义一个字节数组
        byte[] secretBytes = null;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //对字符串进行加密
            md.update(plainText.getBytes());
            //获得加密后的数据
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        //将加密后的数据转换为16进制数字
//        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位，需要前面补0
//        for (int i = 0; i < 32 - md5code.length(); i++) {
//            md5code = "0" + md5code;
//        }
        return  byteHEX(secretBytes);
    }

    public static String byteHEX(byte[] ib) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F' };
        StringBuilder sb =new StringBuilder();
        for (int i = 0; i < 16; i++) {
            char[] ob = new char[2];
            ob[0] = Digit[(ib[i] >>> 4) & 0X0F];
            ob[1] = Digit[ib[i] & 0X0F];
            sb.append(new String(ob));
        }

        return sb.toString();
    }

}
